package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Transactional
    @Override
    public R addOrders(Orders orders) {

        //获取用户id
        Long userId = UserHolder.getUserId();

        //通过用户id获取购物车数据
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(qw);
        if (list==null||list.size()==0){
            return R.error("购物车为空,无法下单");
        }

        //获取用户信息
        User user = userService.getById(userId);

        //根据前端传来的地址id查询地址
        AddressBook address = addressBookService.getById(orders.getAddressBookId());
        if (address==null){
            return R.error("用户地址有误,请重新输入");
        }

        //获取一个订单号
        long id = IdWorker.getId();//订单号


        //获取订单总价
        BigDecimal bigDecimal = new BigDecimal(0);

        //将购物车查询的数据进行封装添加到orderdetail订单明细表中
/*        List<OrderDetail> orderDetails = list.stream().map(shoppingCart -> {
            OrderDetail detail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, detail, "id");
            detail.setOrderId(id);
            BigDecimal price = detail.getAmount();
            BigDecimal number = new BigDecimal(detail.getNumber());
            //该类商品的总价
            detail.setAmount(price.multiply(number));
            //将该类商品总价进行添加计算到订单总价中
            bigDecimal.add(detail.getAmount());
            orderDetailService.save(detail);
            return detail;
        }).collect(Collectors.toList());*/
        List<OrderDetail> orderDetails =new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail detail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, detail, "id");
            detail.setOrderId(id);
            BigDecimal price = detail.getAmount();
            BigDecimal number = new BigDecimal(detail.getNumber());
            //该类商品的总价
            detail.setAmount(price.multiply(number));
            //将该类商品总价进行添加计算到订单总价中
            bigDecimal= bigDecimal.add(detail.getAmount());
            orderDetailService.save(detail);
            orderDetails.add(detail);
        }

        //将前端传的数据进行处理添加到orders订单表中
        //订单号
        orders.setNumber(String.valueOf(id));
        //订单状态
        orders.setStatus(2);
        //下单用户id
        orders.setUserId(UserHolder.getUserId());
        //地址
        orders.setAddress((address.getProvinceName() == null ? "" : address.getProvinceName())
                + (address.getCityName() == null ? "" : address.getCityName())
                + (address.getDistrictName() == null ? "" : address.getDistrictName())
                + (address.getDetail() == null ? "" : address.getDetail()));
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //实收金额
        orders.setAmount(bigDecimal);
        //用户名
        String userName = userService.getById(userId).getName();
        orders.setUserName(userName);
        //手机号
        orders.setPhone(address.getPhone());
        //收货人
        orders.setConsignee(address.getConsignee());
        this.save(orders);

        //删除当前用户的购物车数据
        shoppingCartService.remove(qw);

        return R.success("清空购物车成功");





    }
}
